package MD5Test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.security.MessageDigest;

public class ZgjGetMD5 {


	static char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	public static void writeFile(String filePathAndName, String fileContent) {
		try {
			File f = new File(filePathAndName);
			if (!f.exists()) {

				f.createNewFile();
			}
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"gbk");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write(fileContent);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getMD5(File file) {
		FileInputStream fis = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			fis = new FileInputStream(file);
			byte[] buffer = new byte[2048];
			int length = -1;
			while ((length = fis.read(buffer)) != -1) {
				md.update(buffer, 0, length);
			}
			byte[] b = md.digest();
			System.out.println(b.length);
			return byteToHexString(b);
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;

		} finally {
			try {
				fis.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	public static String getMD5(String ss) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(ss.getBytes(Charset.forName("gbk")));
			byte[] b = md.digest();
			System.out.println(b.length);
			return byteToHexString(b);
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;

		}
	}


	private static String byteToHexString(byte[] tmp) {
		String s;
		char str[] = new char[16 * 2];
		int k = 0; 
		for (int i = 0; i < 16; i++) { 
			byte byte0 = tmp[i]; 
			str[k++] = hexdigits[byte0 >>> 4 & 0xf]; 
			str[k++] = hexdigits[byte0 & 0xf]; 
		}
		s = new String(str); 
		return s;
	}

	public static void main(String arg[]) {
		String s1 = getMD5(new File("b.txt"));
		String s3 = getMD5(new File("a.txt"));
		String s2 = getMD5(new File("fileWBS_WT_CASH_2014-08-12_16-30-42.txt"));
//		String s2 = getMD5("<?xml version=��>");
		writeFile("bbbbb.txt", "<?xml version=赖?>\r");
		String ssss = new String("<?xml version=赖?>\r");
		writeFile("bbbbbccccc.txt", ssss);
		System.out.println(ssss);
		System.out.println("s1:" + s1);
		System.out.println("s2:" + s2);
		System.out.println("s3:" + s3);
	}

}